package template.page.user;

import java.util.List;
import java.util.Locale;

import org.apache.click.ActionListener;
import org.apache.click.Context;
import org.apache.click.Control;
import org.apache.click.control.AbstractLink;
import org.apache.click.control.ActionLink;
import org.apache.click.control.Column;
import org.apache.click.control.FieldSet;
import org.apache.click.control.Label;
import org.apache.click.control.PageLink;
import org.apache.click.control.Table;
import org.apache.click.dataprovider.DataProvider;
import org.apache.click.extras.control.LinkDecorator;
import org.apache.click.util.HtmlStringBuffer;

import template.page.BorderPage;
import cvcg.model.GameSession;
import cvcg.model.Player;
import cvcg.util.GameSessionStatusDecorator;

@SuppressWarnings("serial")
public class HomePage extends BorderPage {

    public String title = "Game Sessions";
   
	private Table phase1GameSessionTable = new Table("phase1GameSessionTable");	
	private Table phase2GameSessionTable = new Table("phase2GameSessionTable");
	private Table closedGameSessionTable = new Table("closedGameSessionTable");
	private Table gameSessionSingleTable = new Table("gameSessionSingleTable");
	private PageLink editGameSessionPhase1Link = new PageLink("Detail",GameSessionDetailPhase1.class);
	private PageLink editGameSessionPhase2Link = new PageLink("Detail",GameSessionDetailPhase2.class);
	private PageLink viewGameSessionClosedLink = new PageLink("Detail",GameSessionDetailClosed.class);
	private PageLink genericPageLink = new PageLink("Detail");
	private ActionLink joinGameSessionPhase1Link = new ActionLink("Join",this,"onJoinGameSessionLinkClick");	
	private FieldSet phase1FieldSet = new FieldSet("phase1");
	private FieldSet phase2FieldSet = new FieldSet("phase2");
	private FieldSet phase3FieldSet = new FieldSet("phase3");
	private FieldSet singleFieldSet = new FieldSet("single");
	private Label imagePhase1 = new Label("imagePhase1","Phase <IMG style=\"margin-bottom:-3px;padding-right:5px;\" alt=\"phase1\" src=\"../assets/images/_number_1_16x16.png\"/> = Game List");
	private Label imagePhase2 = new Label("imagePhase2","Phase <IMG style=\"margin-bottom:-3px;padding-right:5px;\" alt=\"phase2\" src=\"../assets/images/_number_2_16x16.png\"/> = Top 5");
	private Label imagePhase3 = new Label("imagePhase3","Phase <IMG style=\"margin-bottom:-3px;padding-right:5px;\" alt=\"phase3\" src=\"../assets/images/_number_3_16x16.png\"/> = Results");	
			
	public HomePage() 
	{
		getContext().setLocale(Locale.FRENCH);
		addControl(joinGameSessionPhase1Link);
		addControl(editGameSessionPhase1Link);
		addControl(editGameSessionPhase2Link);
		addControl(viewGameSessionClosedLink);				
		
		phase1FieldSet.setLegend("Phase 1 Sessions (Game List)");
		phase2FieldSet.setLegend("Phase 2 Sessions (Top 5)");
		phase3FieldSet.setLegend("Phase 3 Sessions (Results)");
		singleFieldSet.setLegend("Sessions");
		setFieldSetStyle(phase1FieldSet);
		setFieldSetStyle(phase2FieldSet);
		setFieldSetStyle(phase3FieldSet);
		setFieldSetStyle(singleFieldSet);
		
		editGameSessionPhase1Link.setImageSrc("/assets/images/actionEdit.gif");
		editGameSessionPhase1Link.setTitle("Edit Session");		
		editGameSessionPhase2Link.setImageSrc("/assets/images/actionEdit.gif");
		editGameSessionPhase2Link.setTitle("Edit Session");
		viewGameSessionClosedLink.setImageSrc("/assets/images/_glass_24x24.png");
		viewGameSessionClosedLink.setTitle("View Session");		
	}
	
	private void setFieldSetStyle(FieldSet fieldSet) 
	{
		//width:550px;margin-bottom:20px;padding:15px;
		fieldSet.setStyle("width","570px");
		fieldSet.setStyle("margin-bottom","20px");
		fieldSet.setStyle("padding","15px");
		fieldSet.setLegendAttribute("style","font-weight:bold");
	}
	private void buildMultiTable() 
	{
		phase1FieldSet.add(phase1GameSessionTable);
		phase2FieldSet.add(phase2GameSessionTable);
		phase3FieldSet.add(closedGameSessionTable);
		
		buildTable(phase1GameSessionTable);
		buildTable(phase2GameSessionTable);
		buildTable(closedGameSessionTable);		

		addControl(phase1GameSessionTable);
		addControl(phase2GameSessionTable);
		addControl(closedGameSessionTable);
	}
	
	private void buildSingleTable() 
	{		
		singleFieldSet.add(imagePhase1);
		singleFieldSet.add(imagePhase2);
		singleFieldSet.add(imagePhase3);		
		buildSingleTable(gameSessionSingleTable);
		singleFieldSet.add(gameSessionSingleTable);		
		addControl(gameSessionSingleTable);
		
	}
	
	@SuppressWarnings("rawtypes")
	public void buildTable(final Table table) 
	{
		final String currentUser = getCurrentUser();
		table.setClass(Table.CLASS_ITS);		
		table.setShowBanner(false);
		table.setSortable(false);		
				
		Column dateColumn = new Column("Date");
		dateColumn.setWidth("25%");
		//dateColumn.setFormat("{0,date,dd/MM/yyyy HH:mm}");
		dateColumn.setFormat("{0,date,dd MMMM yyyy}");
		table.addColumn(dateColumn);		
		table.addColumn(new Column("playerCount"));
		table.addColumn(new Column("totalGameCount"));
		table.addColumn(new Column("knownGameCount"));
				
        Column column = new Column("Action");
        column.setWidth("15%");
        column.setTextAlign("center");
        
        AbstractLink[] links;
    	if (phase1GameSessionTable.equals(table)) 
		{
    		links = new AbstractLink[] { editGameSessionPhase1Link, joinGameSessionPhase1Link };		           
		} else if (phase2GameSessionTable.equals(table))
		{
			links = new AbstractLink[] { editGameSessionPhase2Link};
		} else {
			links = new AbstractLink[] { viewGameSessionClosedLink};
		}
        LinkDecorator decorator = new LinkDecorator(table, links, "id") 
        {
        	protected void renderActionLink(HtmlStringBuffer buffer, AbstractLink link, Context context, Object row, Object value) 
        	{
        		if (row instanceof GameSession) 
        		{
        			GameSession gameSession = (GameSession) row;
        			boolean isUserAttending = gameSession.isPlayerAttendingSession(currentUser);
        			String editImage=null;
        			String editText=null;
        			if (isUserAttending) 
        			{
        				editImage = "/assets/images/actionEdit.gif";
        				editText = "Edit Session";
        			} else {
        				editImage = "/assets/images/_glass_24x24.png";
        				editText = "View Session";
        			}
        			
        			if (joinGameSessionPhase1Link.equals(link)) 
        			{
	        			if (isUserAttending) 
	        			{
	        				link.setLabel("Leave");
	        			} else {
	        				link.setLabel("Join");
	        			}
        			} else if(editGameSessionPhase1Link.equals(link)) 
        			{
        				editGameSessionPhase1Link.setImageSrc(editImage);
        				editGameSessionPhase1Link.setTitle(editText);
        			} else if(editGameSessionPhase2Link.equals(link)) 
        			{        			
        				editGameSessionPhase2Link.setImageSrc(editImage);
        				editGameSessionPhase2Link.setTitle(editText);
        			}
        		}        		        		
        		super.renderActionLink(buffer, link, context, row, value); 	
        	}
        };
                
        column.setDecorator(decorator);
        column.setSortable(false);
        table.addColumn(column);

        // Table rowList will be populated through a DataProvider which loads
        // data on demand.
        table.setDataProvider(new DataProvider() {

            public List getData() {
                return getTableDataProvider(table);
            }
        });

        // Below we setup the table to preserve it's state (sorting and paging)
        // while editing customers
        table.getControlLink().setActionListener(new ActionListener() {

            public boolean onAction(Control source) {
                // Save Table sort and paging state between requests.
                // NOTE: we set the listener on the table's Link control which is invoked
                // when the Link is clicked, such as when paging or sorting.
                // This ensures the table state is only saved when the state changes, and
                // cuts down on unnecessary session replication in a cluster environment.
            	table.saveState(getContext()); 
                return true;
            }
        });

        // Restore the table sort and paging state from the session between requests
        table.restoreState(getContext()); 

	}
	
	@SuppressWarnings("rawtypes")
	private List getTableDataProvider(Table table) 
	{		
		if (phase1GameSessionTable.equals(table)) 
		{
			return gameSessionService.getPhase1GameSessions();   
		} else if (phase2GameSessionTable.equals(table)) 
		{
            return 	gameSessionService.getPhase2GameSessions();        
		} else if (closedGameSessionTable.equals(table)){
			return gameSessionService.getClosedGameSessions();
		} else {
			return gameSessionService.getAllGameSessions();
		}
	}
	
	@SuppressWarnings("rawtypes")
	private void buildSingleTable(final Table table) 
	{
		final String currentUser = getCurrentUser();
		table.setClass(Table.CLASS_ITS);		
		table.setShowBanner(false);
		table.setSortable(false);
				
		Column dateColumn = new Column("Date");
		dateColumn.setWidth("25%");		
		dateColumn.setFormat("{0,date,dd MMMM yyyy}");
		table.addColumn(dateColumn);
		Column playerCountColumn = new Column("playerCount");
		playerCountColumn.setTextAlign("center");
		
		Column totalGameCountColumn = new Column("totalGameCount");
		totalGameCountColumn.setTextAlign("center");
		
		Column knownGameCountColumn = new Column("knownGameCount");
		knownGameCountColumn.setTextAlign("center");
		
		table.addColumn(playerCountColumn);
		table.addColumn(totalGameCountColumn);
		table.addColumn(knownGameCountColumn);
		
		Column statusColumn = new Column("status");
		statusColumn.setTextAlign("center");
		statusColumn.setDecorator(new GameSessionStatusDecorator());
		table.addColumn(statusColumn);
		table.setSortedColumn("Date");

        Column joinColumn = new Column("Join");
        joinColumn.setWidth("15%");
        joinColumn.setHeaderTitle("Join / Leave");
        joinColumn.setTextAlign("center");
        
        LinkDecorator joinDecorator = new LinkDecorator(table, joinGameSessionPhase1Link, "id") 
        {
        	protected void renderActionLink(HtmlStringBuffer buffer, AbstractLink link, Context context, Object row, Object value) 
        	{
        		if (row instanceof GameSession) 
        		{
        			GameSession gameSession = (GameSession) row;
        			if (GameSession.STATUS_PHASE1.equals(gameSession.getStatus())) 
        			{
        				link.setDisabled(false);
	        			if (gameSession.isPlayerAttendingSession(currentUser)) 
	        			{
	        				link.setLabel("Leave");
	        			} else {
	        				link.setLabel("Join");
	        			}
        			} else {
        				link.setDisabled(true);
        				link.setLabel("");
        			}
        		}        		        		
        		super.renderActionLink(buffer, link, context, row, value); 	
        	}
        };

        joinColumn.setDecorator(joinDecorator);
        joinColumn.setSortable(false);
        table.addColumn(joinColumn);

        Column actionColumn = new Column("Action");
        actionColumn.setWidth("15%");
        actionColumn.setTextAlign("center");
                       
        LinkDecorator actionDecorator = new LinkDecorator(table, genericPageLink, "id") 
        {
        	protected void renderActionLink(HtmlStringBuffer buffer, AbstractLink link, Context context, Object row, Object value) 
        	{
        		if (row instanceof GameSession && link instanceof PageLink) 
        		{
        			PageLink pageLink = (PageLink) link;
        			GameSession gameSession = (GameSession) row;
        			String editImage=null;
        			String editText=null;
        			if (gameSession.isPlayerAttendingSession(currentUser)) 
        			{
        				editImage = "/assets/images/actionEdit.gif";
        				editText = "Edit Session";
        			} else {
        				editImage = "/assets/images/_glass_24x24.png";
        				editText = "View Session";
        			}
        			if (GameSession.STATUS_PHASE1.equals(gameSession.getStatus())) 
        			{
        				pageLink.setImageSrc(editImage);
        				pageLink.setTitle(editText);
        				pageLink.setPageClass(GameSessionDetailPhase1.class);
        			} else if (GameSession.STATUS_PHASE2.equals(gameSession.getStatus())) 
        			{
        				pageLink.setImageSrc(editImage);
        				pageLink.setTitle(editText);
        				pageLink.setPageClass(GameSessionDetailPhase2.class);
        			} else {       				
        				pageLink.setImageSrc("/assets/images/_glass_24x24.png");
        				pageLink.setTitle("View Session");
        				pageLink.setPageClass(GameSessionDetailClosed.class);
        			}
        		}        		        		
        		super.renderActionLink(buffer, link, context, row, value); 	
        	}
        };
                
        actionColumn.setDecorator(actionDecorator);
        actionColumn.setSortable(false);
        table.addColumn(actionColumn);

        // Table rowList will be populated through a DataProvider which loads
        // data on demand.
        table.setDataProvider(new DataProvider() {

            public List getData() {
                return getTableDataProvider(table);
            }
        });

        // Below we setup the table to preserve it's state (sorting and paging)
        // while editing customers
        table.getControlLink().setActionListener(new ActionListener() {

            public boolean onAction(Control source) {
                // Save Table sort and paging state between requests.
                // NOTE: we set the listener on the table's Link control which is invoked
                // when the Link is clicked, such as when paging or sorting.
                // This ensures the table state is only saved when the state changes, and
                // cuts down on unnecessary session replication in a cluster environment.
            	table.saveState(getContext()); 
                return true;
            }
        });

        // Restore the table sort and paging state from the session between requests
        table.restoreState(getContext()); 
	}
	public boolean onJoinGameSessionLinkClick() {
		String currentUser = getCurrentUser();
		Long id = joinGameSessionPhase1Link.getValueLong();
		gameSessionService.toggleGameSessionUser(id,currentUser);
		return true;
	}
	
    @Override
    public void onGet() 
    {
    	String currentUser = getCurrentUser();
    	Player player = gameSessionService.getPlayerByName(currentUser);
    	if (player!=null) 
    	{
    		if (player.getMultiTable()) 
    		{
    			buildMultiTable();
    		} else {
    			buildSingleTable();
    		}
    	}
    }

}
